<?php

namespace Trawind\Helpers;

/**
 * Class MathHelper
 * @package Trawind\Helpers
 */
class MathHelper
{


    protected $_result = null;


    protected $scale;


    /**
     * MathHelper constructor.
     * @param  int  $scale
     */
    public function __construct(int $scale)
    {
        $this->scale = $scale;
    }


    /**
     * @note 由于bc库单次只能计算两个值。链式计算，不识别先乘除后加减！
     * @example
     * MathHelper::factory()
        ->add(...[2.2,3.4])
        ->sub(...[1.1,1])
        ->mul(...[2])
        ->div(...[3])
        ->result();
     * @param  int  $scale
     * @return static
     */
    public static function factory(int $scale = 2)
    {
        return new static($scale);
    }


    /**
     * [ + ]
     * @param ...$values
     * @return $this
     */
    public function add(...$values)
    {
        $this->compute('bcadd', ...$values);
        return $this;
    }


    /**
     * [ - ]
     * @param ...$values
     * @return $this
     */
    public function sub(...$values)
    {
        $this->compute('bcsub', ...$values);
        return $this;
    }


    /**
     * [ * ]
     * @param ...$values
     * @return $this
     */
    public function mul(...$values)
    {
        $this->compute('bcmul', ...$values);
        return $this;
    }


    /**
     * [ / ]
     * @param ...$values
     * @return $this
     */
    public function div(...$values)
    {
        $this->compute('bcdiv', ...$values);
        return $this;
    }


    /**
     * @return null
     */
    public function result()
    {
        return $this->_result;
    }


    /**
     * @param $method
     * @param ...$values
     */
    protected function compute($method, ...$values)
    {
        if (is_null($this->_result)) {
            $this->_result = $values[0];
            array_shift($values);
        }

        foreach ($values as $index => $value) {
            $this->_result = $method($this->_result, $value, $this->scale + 1);
        }

        $this->_result = round($this->_result, $this->scale);
    }
}